package com.zhanghe.study.io.old;

import java.io.*;

/**
 * 缓冲流
 */
public class TestBufferedInputOutputStream {
    public static void main(String[] args) {
        copyFile("Type.png","Type_copy.png");
    }

    /**
     * 使用缓冲流复制文件
     * @param src
     * @param target
     */
    private static void copyFile(String src,String target){
        File srcFile = new File(src);
        File targetFile = new File(target);
        FileInputStream fis = null;
        FileOutputStream fos = null;
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try{
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(targetFile);
            bufferedInputStream = new BufferedInputStream(fis);
            bufferedOutputStream = new BufferedOutputStream(fos);
            byte[] b = new byte[10];
            int len;
            while ((len = bufferedInputStream.read(b)) != -1){
                bufferedOutputStream.write(b,0,len);
                // 写完之后flush
                bufferedOutputStream.flush();
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if(bufferedInputStream != null){
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(bufferedOutputStream != null){
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
